package com.synnex.mobile.servier.web.activeRecord.controller.admin;

import com.sun.jndi.toolkit.url.UrlUtil;
import com.synnex.mobile.generic.core.exception.BusinessException;
import com.synnex.mobile.generic.core.exception.SystemException;
import com.synnex.mobile.generic.core.util.MultiValueMap;
import com.synnex.mobile.generic.core.util.ObjectUtil;
import com.synnex.mobile.generic.core.util.StringUtil;
import com.synnex.mobile.generic.core.util.URLUtils;
import com.synnex.mobile.generic.log.dao.annotation.LogClass;
import com.synnex.mobile.generic.log.dao.annotation.LogMethod;
import com.synnex.mobile.generic.log.entity.LogEntry;
import com.synnex.mobile.generic.web.anotation.mapping.RequestMapping;
import com.synnex.mobile.generic.web.view.ModelAndView;
import com.synnex.mobile.generic.web.view.RedirectView;
import com.synnex.mobile.generic.web.view.View;
import com.synnex.mobile.servier.core.actRecord.bo.ActivityRecordBo;
import com.synnex.mobile.servier.core.actRecord.bo.FolderBo;
import com.synnex.mobile.servier.web.activeRecord.controller.AbstractActiveRecordController;
import com.synnex.mobile.servier.web.activeRecord.form.ActRecordForm;
import com.synnex.mobile.servier.web.activeRecord.form.FolderForm;
import com.synnex.mobile.servier.web.contact.form.ContactForm;
import com.synnex.mobile.servier.web.utils.DateUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author kerryf
 */
@RequestMapping(url = "/admin")
@LogClass(name = "admin activity record")
public class AdminActiveRecordController extends AbstractActiveRecordController {


    @RequestMapping(url = "/listActRecord.do")
    @LogMethod(name = "get activity record list ")
    public ModelAndView listActRecord(HttpServletRequest request, HttpServletResponse response) {
        try {

            Map<String, Object> model = new HashMap<String, Object>();
            String key = request.getParameter("title");
            String cate = request.getParameter("cate");
            List<ActivityRecordBo> recordBos = actRecordService.ListActRecord(key, cate);
            model.put("results", recordBos);
            model.put("totalCount", recordBos.size());
            model.put("cate", cate);

            return new ModelAndView(model);

        } catch (Exception e) {
            throw new SystemException(e);
        }
    }

    @RequestMapping(url = "/addActRecord.do")
    @LogMethod(name = "jump to add activity record page")
    public ModelAndView addActRecord(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object> model = new HashMap<String, Object>();
            String cate = request.getParameter("cate");
            List<FolderBo> folderBoList = actRecordService.ListFolder(cate);
            model.put("cate", cate);
            model.put("folders", folderBoList);
            return new ModelAndView(model);

        } catch (Exception e) {
            throw new SystemException(e);
        }
    }

    @RequestMapping(url = "/addActRecordAction.do", formCommand = "addActRecord")
    @LogMethod(name = "add a new activity record")
    public ModelAndView addActRecordAction(HttpServletRequest request, HttpServletResponse response, ActRecordForm form) {

        LogEntry log = this.getAdminSession(request).getCurrentLogEntry(request);
        try {
            ActivityRecordBo bo = new ActivityRecordBo();
            String title = request.getParameter("title");
            String seq = request.getParameter("seq");
            String cate = request.getParameter("cate");
            String date = request.getParameter("activityDay");

            bo.setTitle(title);
            bo.setActivityDay(DateUtil.strToDate(date));
            bo.setCategory(cate);
            bo.setFolderId(form.getFolderId());

            if (seq == null || seq.equals("") || !StringUtil.isInteger(seq)) {
                bo.setSeq(99);
            } else {
                bo.setSeq(Integer.parseInt(seq));
            }

            MultiValueMap url = uploadFilesToFtp(request, "fileName", null);
            if (null != url.get("fileName")) {
                String name = url.get("fileName").toString();
                if (name.endsWith("pdf")) {
                    bo.setType("pdf");
                } else {
                    bo.setType("mp4");
                }
                bo.setPath(name.substring(1, name.length() - 1));
            }

            actRecordService.addActRecord(bo);

            log.setItemText(bo.toString());

            Map<String, Object> model = new HashMap<String, Object>();
            model.put("cate", cate);

            return new ModelAndView(new RedirectView("/admin/listActRecord.do"), model);

        } catch (Exception e) {
            throw new SystemException(e);
        }
    }

    @RequestMapping(url = "/viewActRecord.do")
    @LogMethod(name = "view activity record by id")
    public ModelAndView viewActRecord(HttpServletRequest request, HttpServletResponse response) {

        LogEntry log = this.getAdminSession(request).getCurrentLogEntry(request);
        Map<String, Object> model = new HashMap<String, Object>();

        String id = request.getParameter("id");

        ActivityRecordBo bo = actRecordService.getActRecordBoById(Integer.parseInt(id));
        List<FolderBo> folderBoList = actRecordService.ListFolder(request.getParameter("cate"));
        model.put("folders", folderBoList);
        model.put("data", bo);
        model.put("cate", request.getParameter("cate"));

        log.setItemText(id);

        return new ModelAndView(model);
    }

    @RequestMapping(url = "/editActRecord.do", formCommand = "viewActRecord")
    @LogMethod(name = "edit record by id")
    public ModelAndView editActRecord(HttpServletRequest request, HttpServletResponse response, ActRecordForm form) {

        LogEntry log = this.getAdminSession(request).getCurrentLogEntry(request);
        ActivityRecordBo bo = new ActivityRecordBo();
        String title = request.getParameter("title");
        String seq = request.getParameter("seq");
        String path = request.getParameter("path");
        String date = request.getParameter("activityDay");
        String entryDate = request.getParameter("entryDate");
        String id = request.getParameter("id");
        String cate = request.getParameter("cate");
        String folderId = request.getParameter("folderId");

        bo.setTitle(title);
        bo.setActivityDay(DateUtil.strToDate(date));
        bo.setEntryDate(DateUtil.strToDate(entryDate));
        bo.setId(Integer.parseInt(id));
        bo.setCategory(cate);
        bo.setFolderId(form.getFolderId());

        if (seq == null || seq.equals("") || !StringUtil.isInteger(seq)) {
            bo.setSeq(99);
        } else {
            bo.setSeq(Integer.parseInt(seq));
        }
        String fileName = null;
        if (path != null && !path.equals("")) {
            fileName = path.substring(path.lastIndexOf("/") + 1, path.lastIndexOf("."));
        }
        MultiValueMap url = uploadFilesToFtp(request, "fileName", fileName);
        if (null != url.get("fileName")) {
            String name = url.get("fileName").toString();
            if (name.endsWith("pdf")) {
                bo.setType("pdf");
            } else {
                bo.setType("mp4");
            }
            bo.setPath(name.substring(1, name.length() - 1));
        } else {
            if (fileName.endsWith("pdf")) {
                bo.setType("pdf");
            } else {
                bo.setType("mp4");
            }
            bo.setPath(path);
        }

        if (form.getSeq() == null || form.getSeq().equals("") || !StringUtil.isInteger(form.getSeq())) {
            bo.setSeq(99);
        } else {
            bo.setSeq(Integer.parseInt(form.getSeq()));
        }
        actRecordService.editActRecord(bo);
        log.setItemText(bo.toString());


        return new ModelAndView(new RedirectView("/admin/listActRecord.do?cate=" + cate));
    }

    @RequestMapping(url = "/downLoadFile.do")
    @LogMethod(name = "download record file")
    public ModelAndView downLoadFile(HttpServletRequest request, HttpServletResponse response) {

        LogEntry log = this.getAdminSession(request).getCurrentLogEntry(request);
        try {
            String downLoadLink = "http://" + this.getConfig().getFtpHost() + this.getConfig().getFtpDownLoadPath() + "/";
            String idStr = request.getParameter("id");
            if (StringUtil.isEmpty(idStr) || !StringUtil.isInteger(idStr)) {
                throw new BusinessException("Doc ID is invalid.");
            }
            ActivityRecordBo record = actRecordService.getActRecordBoById(Integer.valueOf(idStr));
            if (record.getPath() != null) {
                //judge the doc is a file
                URL url = new URL(downLoadLink + record.getPath());
                URLConnection connection = url.openConnection();
                connection.setConnectTimeout(10 * 60 * 1000);
                InputStream in = connection.getInputStream();
                response.setContentType(connection.getContentType());
                response.setHeader("Content-Disposition", "attachment;filename=servier-" + System.currentTimeMillis() + "." + record.getPath().substring(record.getPath().indexOf(".")));
                byte[] buffer = new byte[1204];
                int byteread;
                while ((byteread = in.read(buffer)) != -1) {
                    response.getOutputStream().write(buffer, 0, byteread);
                }
                log.setItemText("record: " + idStr);
                return null;

            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new SystemException("Unable to download document, please try again later.");
        }
        return null;
    }


    @RequestMapping(url = "/deleteActRecord.do")
    @LogMethod(name = "delete record by id")
    public ModelAndView deleteActRecord(HttpServletRequest request, HttpServletResponse response) {

        LogEntry log = this.getAdminSession(request).getCurrentLogEntry(request);
        Map<String, Object> model = new HashMap<String, Object>();

        String id = request.getParameter("id");
        String cate = request.getParameter("cate");
        actRecordService.deleteActRecordById(Integer.parseInt(id));

        log.setItemText("delete activity record, id is " + id);

        View view = new RedirectView("/admin/listActRecord.do");
        model.put("cate", cate);
        return new ModelAndView(view, model);
    }


    /////////////////////////////////////
    @LogMethod(name = "list to folder")
    @RequestMapping(url = "/folder/listFolder.do")
    public ModelAndView listFolder(HttpServletRequest request, HttpServletResponse response) {

        Map<String, Object> model = new HashMap<String, Object>();

        String cate = request.getParameter("cate");
        List<FolderBo> folderBoList = actRecordService.ListFolder(cate);

        model.put("results", folderBoList);
        model.put("totalCount", folderBoList.size());
        model.put("cate", cate);

        return new ModelAndView(model);
    }

    @RequestMapping(url = "/folder/addFolder.do")
    @LogMethod(name = "jump to add folder page")
    public ModelAndView addFolder(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object> model = new HashMap<String, Object>();
            return new ModelAndView(model);

        } catch (Exception e) {
            throw new SystemException(e);
        }
    }


    @RequestMapping(url = "/folder/addFolderAction.do", formCommand = "addFolder")
    @LogMethod(name = "add a new activity record")
    public ModelAndView addFolderAction(HttpServletRequest request, HttpServletResponse response, FolderForm form) {

        LogEntry log = this.getAdminSession(request).getCurrentLogEntry(request);
        try {
//            ActivityRecordBo bo = new ActivityRecordBo();
//            String title = request.getParameter("title");
            String seq = request.getParameter("seq");
//            String cate = request.getParameter("cate");
//            String date = request.getParameter("activityDay");
//
//            bo.setTitle(title);
//            bo.setActivityDay(DateUtil.strToDate(date));
//            bo.setCategory(cate);
            FolderBo bo = ObjectUtil.copyProperties(form, FolderBo.class);

            if (seq == null || seq.equals("") || !StringUtil.isInteger(seq)) {
                bo.setSeq(99);
            } else {
                bo.setSeq(Integer.parseInt(seq));
            }

            actRecordService.addFolder(bo);

            log.setItemText(bo.toString());

            Map<String, Object> model = new HashMap<String, Object>();
            model.put("cate", form.getCategory());

            return new ModelAndView(new RedirectView("/admin/folder/listFolder.do"), model);

        } catch (Exception e) {
            throw new SystemException(e);
        }
    }

    @RequestMapping(url = "/folder/viewFolder.do")
    @LogMethod(name = "jump to view folder page")
    public ModelAndView viewFolder(HttpServletRequest request, HttpServletResponse response) {
        try {
            String id = request.getParameter("id");
            String cate = request.getParameter("cate");
            FolderBo folderBo = actRecordService.getFolderBoById(Integer.parseInt(id));
            Map<String, Object> model = new HashMap<String, Object>();
            model.put("data", folderBo);
            model.put("cate", cate);
            return new ModelAndView(model);

        } catch (Exception e) {
            throw new SystemException(e);
        }
    }


    @RequestMapping(url = "/folder/editFolderAction.do", formCommand = "viewFolder")
    @LogMethod(name = "add a new activity record")
    public ModelAndView editFolderAction(HttpServletRequest request, HttpServletResponse response, FolderForm form) {

        LogEntry log = this.getAdminSession(request).getCurrentLogEntry(request);
        try {
//            ActivityRecordBo bo = new ActivityRecordBo();
//            String title = request.getParameter("title");
            String seq = request.getParameter("seq");
//            String cate = request.getParameter("cate");
//            String date = request.getParameter("activityDay");
//
//            bo.setTitle(title);
//            bo.setActivityDay(DateUtil.strToDate(date));
//            bo.setCategory(cate);
            FolderBo bo = ObjectUtil.copyProperties(form, FolderBo.class);

            if (seq == null || seq.equals("") || !StringUtil.isInteger(seq)) {
                bo.setSeq(99);
            } else {
                bo.setSeq(Integer.parseInt(seq));
            }

            actRecordService.editFolder(bo);

            log.setItemText(bo.toString());

            Map<String, Object> model = new HashMap<String, Object>();
            model.put("cate", form.getCategory());

            return new ModelAndView(new RedirectView("/admin/folder/listFolder.do"), model);

        } catch (Exception e) {
            throw new SystemException(e);
        }
    }

    @RequestMapping(url = "/folder/deleteFolder.do")
    @LogMethod(name = "delete a folder")
    public ModelAndView deleteFolder(HttpServletRequest request, HttpServletResponse response) {

        LogEntry log = this.getAdminSession(request).getCurrentLogEntry(request);
        try {
            String id = request.getParameter("id");
            String cate = request.getParameter("cate");
            actRecordService.deleteFolderBoById(Integer.parseInt(id));

            log.setItemText("delete by id: " + id);

            Map<String, Object> model = new HashMap<String, Object>();
            model.put("cate", cate);

            return new ModelAndView(new RedirectView("/admin/folder/listFolder.do"), model);

        } catch (Exception e) {
            throw new SystemException(e);
        }
    }
}
